<template>
	<view class="mine-page">
		<!-- 顶部红色渐变区域 -->
		<view class="top-bar">
			<!-- 头像 + 欢迎语 + 用户名 -->
			<view class="user-info">
				<!-- 头像容器（可点击上传） -->
				<view class="avatar-container" @click="handleAvatarClick">
					<image class="avatar" :src="avatarUrl" mode="aspectFill"></image>
				</view>

				<view class="text-group">
					<!-- 未登录时显示点击登录按钮 -->
					<view v-if="!isLogin" class="login-area">
						<text class="welcome-text">HI~欢迎回来</text>
						<view class="login-btn" @click.stop="goToLogin">
							<text class="login-text">点击登录</text>
						</view>
					</view>

					<!-- 登录后显示用户名 -->
					<view v-else class="login-area">
						<text class="welcome-text">HI~欢迎回来</text>
						<text class="username">{{ username }}</text>
					</view>
				</view>
			</view>

			<!-- 关注/话题统计 -->
			<view class="stats">
				<text>关注3</text>
				<text class="divider">|</text>
				<text>话题0</text>
			</view>
		</view>

		<!-- 功能图标区 -->
		<view class="func-icons">
			<view class="func-item" @click="goToCollect">
				<uni-icons type="star-o" size="36" color="#ff4d4f"></uni-icons>
				<text class="text">收藏</text>
			</view>
			<view class="func-item" @click="goToHistory">
				<uni-icons type="clock" size="36" color="#ff4d4f"></uni-icons>
				<text class="text">历史</text>
			</view>
			<view class="func-item" @click="goToSetting">
				<uni-icons type="gear" size="36" color="#ff4d4f"></uni-icons>
				<text class="text">设置</text>
			</view>
		</view>

		<!-- 广告横幅 -->
		<view class="ad-banner">
			<text class="ad-text">瓜分30万现金红包</text>
			<text class="ad-btn">速抢 >></text>
		</view>

		<!-- 内容功能区 -->
		<view class="content-area">
			<view class="content-icons">
				<view class="content-icon video"></view>
				<view class="content-icon pic"></view>
				<view class="content-icon link"></view>
			</view>
			<text class="stats-text">已有385,893人</text>
			<text class="stats-text">在这里发布身边的新鲜事</text>
		</view>

		<!-- 底部Tab栏 - 保持原有图标 -->
		<view class="tab-bar">
			<view class="tab-item" @click="switchTab('news')">
				<uni-icons type="home" size="34" color="#999"></uni-icons>
				<text class="tab-text">新闻</text>
			</view>
			<view class="tab-item" @click="switchTab('video')">
				<uni-icons type="video" size="34" color="#999"></uni-icons>
				<text class="tab-text">视频</text>
			</view>
			<view class="tab-item" @click="switchTab('topic')">
				<uni-icons type="chatbubble-o" size="34" color="#999"></uni-icons>
				<text class="tab-text">话题</text>
			</view>
			<view class="tab-item">
				<uni-icons type="contact" size="34" :color="isLogin ? '#ff4d4f' : '#999'"></uni-icons>
				<text class="tab-text" :style="{ color: isLogin ? '#ff4d4f' : '#999' }">
					{{ isLogin ? '我的' : '未登录' }}
				</text>
			</view>
		</view>

		<!-- 隐藏的Canvas（用于图片裁剪） -->
		<canvas type="2d" id="avatarCanvas" class="hidden-canvas"></canvas>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isLogin: false,
				username: '',
				avatarUrl: '/static/images/default-avatar.png'
			};
		},
		onLoad() {
			console.log('个人页面加载');
			this.loadUserInfo();
			// 监听登录成功事件
			uni.$on('userLoginSuccess', this.onUserLoginSuccess);
		},
		onShow() {
			console.log('个人页面显示');
			// 每次显示都重新加载用户信息
			this.loadUserInfo();
		},
		onUnload() {
			// 移除事件监听
			uni.$off('userLoginSuccess', this.onUserLoginSuccess);
		},
		methods: {
			// 加载用户信息
			loadUserInfo() {
				console.log('开始加载用户信息');

				// 从多个可能的存储位置获取登录状态
				const isLogin = uni.getStorageSync('isLogin');
				const currentUser = uni.getStorageSync('currentUser');
				const userInfo = uni.getStorageSync('userInfo');
				const loginUser = uni.getStorageSync('loginUser'); // 兼容旧版本

				console.log('存储数据:', {
					isLogin,
					currentUser,
					userInfo,
					loginUser,
					registeredUsers: uni.getStorageSync('registeredUsers')?.length || 0
				});

				// 优先使用 currentUser，然后是 loginUser
				let username = currentUser || loginUser || '';

				// 检查是否真的有登录状态
				if (isLogin && username) {
					this.isLogin = true;
					this.username = username;
					console.log('用户已登录:', username);

					// 获取头像
					if (userInfo && userInfo.avatar) {
						this.avatarUrl = userInfo.avatar;
					} else {
						const savedAvatar = uni.getStorageSync('userAvatar');
						if (savedAvatar) {
							this.avatarUrl = savedAvatar;
						}
					}
				} else {
					this.isLogin = false;
					this.username = '';
					this.avatarUrl = '/static/images/default-avatar.png';
					console.log('用户未登录');
				}
			},

			// 用户登录成功回调
			onUserLoginSuccess(userInfo) {
				console.log('收到登录成功事件:', userInfo);
				// 短暂延迟后重新加载用户信息
				setTimeout(() => {
					this.loadUserInfo();
				}, 300);
			},

			// 处理头像点击
			handleAvatarClick() {
				if (!this.isLogin) {
					this.goToLogin();
					return;
				}
				this.chooseAvatar();
			},

			// 跳转到登录页面
			goToLogin() {
				console.log('跳转到登录页面');
				uni.navigateTo({
					url: '/pages/login/login',
					success: () => {
						console.log('跳转成功');
					},
					fail: (err) => {
						console.error('跳转失败:', err);
					}
				});
			},

			// 选择本地图片作为头像
			chooseAvatar() {
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					sizeType: ['compressed'],
					success: (res) => {
						const tempPath = res.tempFilePaths[0];
						this.cropAvatar(tempPath);
					},
					fail: (err) => {
						if (err.errMsg !== 'chooseImage:fail cancel') {
							uni.showToast({
								title: '选择图片失败',
								icon: 'none'
							});
						}
					}
				});
			},

			// 裁剪头像
			cropAvatar(tempPath) {
				uni.getImageInfo({
					src: tempPath,
					success: (info) => {
						const side = Math.min(info.width, info.height);
						const x = (info.width - side) / 2;
						const y = (info.height - side) / 2;

						const ctx = uni.createCanvasContext('avatarCanvas', this);
						ctx.drawImage(tempPath, x, y, side, side, 0, 0, 200, 200);
						ctx.draw(false, () => {
							uni.canvasToTempFilePath({
								canvasId: 'avatarCanvas',
								width: 200,
								height: 200,
								destWidth: 200,
								destHeight: 200,
								success: (res) => {
									this.avatarUrl = res.tempFilePath;

									// 更新存储的头像
									const userInfo = uni.getStorageSync('userInfo') || {};
									userInfo.avatar = res.tempFilePath;
									uni.setStorageSync('userInfo', userInfo);
									uni.setStorageSync('userAvatar', res.tempFilePath);

									uni.showToast({
										title: '头像更新成功',
										icon: 'success'
									});
								}
							}, this);
						});
					}
				});
			},

			// 功能区跳转
			goToCollect() {
				if (!this.isLogin) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				uni.showToast({
					title: '收藏功能开发中',
					icon: 'none'
				});
			},
			goToHistory() {
				if (!this.isLogin) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				uni.showToast({
					title: '历史功能开发中',
					icon: 'none'
				});
			},
			goToSetting() {
				if (!this.isLogin) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					});
					return;
				}
				uni.showToast({
					title: '设置功能开发中',
					icon: 'none'
				});
			},

			// 切换Tab
			switchTab(type) {
				console.log('切换Tab:', type);

				if (type === 'person') {
					// 已经在个人页面
					return;
				}

				// 实际项目中应该跳转到对应页面
				uni.showToast({
					title: `切换到${type}页面`,
					icon: 'none'
				});
			}
		}
	};
</script>

<style scoped>
	.mine-page {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
		padding-bottom: 100rpx;
	}

	/* 顶部红色渐变区域 */
	.top-bar {
		background: linear-gradient(to bottom, #ff4d4f, #ff7a45);
		padding: 30rpx 25rpx 40rpx;
		color: #fff;
	}

	.page-title {
		font-size: 36rpx;
		font-weight: 600;
		display: block;
		text-align: center;
		margin-bottom: 30rpx;
	}

	/* 用户信息区 */
	.user-info {
		display: flex;
		align-items: center;
		gap: 20rpx;
	}

	/* 头像容器 */
	.avatar-container {
		position: relative;
		width: 80rpx;
		height: 80rpx;
	}

	.avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		background-color: #fff;
		border: 2rpx solid rgba(255, 255, 255, 0.8);
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
	}

	.text-group {
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}

	.login-area {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.welcome-text {
		font-size: 28rpx;
	}

	.username {
		color: #fff;
		font-size: 26rpx;
		font-weight: 500;
		background-color: rgba(255, 255, 255, 0.2);
		padding: 6rpx 16rpx;
		border-radius: 20rpx;
		display: inline-block;
	}

	/* 登录按钮样式 */
	.login-btn {
		background-color: #fff;
		color: #ff4d4f;
		padding: 6rpx 20rpx;
		border-radius: 20rpx;
		display: inline-block;
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.login-text {
		font-size: 24rpx;
		font-weight: 500;
	}

	/* 关注/话题统计 */
	.stats {
		margin-top: 15rpx;
		font-size: 24rpx;
		display: flex;
		gap: 15rpx;
		align-items: center;
	}

	.divider {
		color: rgba(255, 255, 255, 0.7);
	}

	/* 功能图标区 */
	.func-icons {
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		padding: 30rpx 0;
		margin: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.func-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 10rpx;
	}

	.func-item .text {
		font-size: 24rpx;
		color: #666;
	}

	/* 广告横幅 */
	.ad-banner {
		background-color: #ff4d4f;
		margin: 0 20rpx;
		border-radius: 10rpx;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.2);
	}

	.ad-text {
		color: #fff;
		font-size: 26rpx;
		font-weight: 500;
	}

	.ad-btn {
		background-color: #fff;
		color: #ff4d4f;
		padding: 5rpx 15rpx;
		border-radius: 20rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	/* 内容功能区 */
	.content-area {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-top: 50rpx;
		gap: 20rpx;
	}

	.content-icons {
		display: flex;
		gap: 40rpx;
	}

	.content-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 10rpx;
	}

	.video {
		background-color: #e1f5fe;
	}

	.pic {
		background-color: #fce4ec;
	}

	.link {
		background-color: #fff8e1;
	}

	.stats-text {
		font-size: 24rpx;
		color: #666;
	}

	/* 底部Tab栏 - 保持原有样式 */
	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		padding: 15rpx 0;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.tab-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #999;
		gap: 5rpx;
	}

	.tab-text {
		font-size: 22rpx;
		color: #999;
	}

	/* 当前选中的Tab项 */
	.tab-item:last-child .tab-text {
		color: #ff4d4f;
	}

	/* 隐藏的Canvas */
	.hidden-canvas {
		position: fixed;
		top: -9999rpx;
		left: -9999rpx;
		width: 200rpx;
		height: 200rpx;
	}
</style>